package com.qf.controller;

import com.qf.pojo.PageBean;
import com.qf.pojo.Profile;
import com.qf.service.ProfileService;
import com.qf.utils.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * @ClassName ProfileServlet
 * @Description TODO
 * @Author CQ
 * @Date 2023/1/30 10:36
 * @Version 1.0
 **/
@WebServlet("/profileservlet")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class ProfileServlet extends BaseServlet{

    ApplicationContext ac =
            new ClassPathXmlApplicationContext("spring-context.xml");


    // 分页查询
    //"profileservlet?method=listProfile&pageNum="
    public String listProfile (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取前端数据
        // 获取页码
        String pageNum = request.getParameter("pageNum");
        // 校验
        int page_num = 1; // 默认从第一页
        int page_size = 8; // 默认每页显示8条数据
        try {
            if (!StringUtils.isEmpty(pageNum)) { // 如果前端给页码
                page_num = Integer.parseInt(pageNum);
                if (page_num <= 0) {
                    page_num = 1;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        // 调用业务逻辑
        try {
            ProfileService profileService = ac.getBean(ProfileService.class);
            PageBean<Profile> pageBean = profileService.findByPage(page_num,page_size);
            // 存储
            request.setAttribute("pageBean",pageBean);
            return "/list.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/login.jsp";
    }

    //详情
    //profileservlet?method=detailProfile&id=${profile.id}">明细
    public String detailProfile (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取数据
        String id = request.getParameter("id");
        if (StringUtils.isEmpty("id")) {
            request.setAttribute("error","id不能为空");
            return "/error.jsp";
        }
        try {
            ProfileService profileService = ac.getBean(ProfileService.class);
            Profile profile = profileService.findDetailById(id);
            request.setAttribute("profile",profile);
            return "/detail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error",e.getMessage());
            return "/error.jsp";
        }
    }
    // 修改
    // profileservlet?method=loadUpdateInfoProfile&id=${profile.id}">修改
    public String loadUpdateInfoProfile (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        String id = request.getParameter("id");
        try {
            ProfileService profileService = ac.getBean(ProfileService.class);
            Profile profile = profileService.findDetailById(id);
            request.setAttribute("updateInfo",profile);
            return "/update.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error",e.getMessage());
            return "/error.jsp";
        }
    }

    // 修改
    // "profileservlet?method=updateProfile&id=${updateInfo.id}
    public String updateProfile (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取数据
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String birthday = request.getParameter("birthday");
        String gender = request.getParameter("gender");
        String career = request.getParameter("career");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");
        // 图片
        Part picture = request.getPart("picture");

        // 4 处理图片
        // 4.1 保存图片
        // 处理IE浏览器
        String uuidFileName = null;
        if (picture != null) {
            String dis = picture.getHeader("Content-Disposition");
            String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
            filename = filename.substring(filename.lastIndexOf("\\") + 1);
            if (!filename.equals("")) {
                // 保存图片
                // 1 生成图片路径
                String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");
                File dir = new File(basePath);
                if (!dir.exists()) {
                    dir.mkdirs(); // 生成图片上传路径
                }
                // 处理后缀
                String ext = filename.substring(filename.lastIndexOf(".") + 1);
                uuidFileName = UUID.randomUUID().toString().replace("-","");
                uuidFileName = uuidFileName + "." + ext;
                picture.write(basePath + File.separator + uuidFileName);
                picture.delete(); // 删除临时文件
                System.out.println("图片保存成功");
            }
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Profile profile = new Profile(Integer.parseInt(id),name,sdf.parse(birthday),gender,career,address,mobile,uuidFileName);
            ProfileService profileService = ac.getBean(ProfileService.class);
            profileService.modify(profile);
            return "redirect:/profileservlet?method=listProfile&pageNum=1";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error",e.getMessage());
            return "/error.jsp";
        }
    }

    // profileservlet?method=imgProfile&id=${profile.id}
    public void imgProfile (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        ProfileService profileService = ac.getBean(ProfileService.class);
        Profile profile = profileService.findDetailById(id);
        String picture = profile.getPicture();
        String basePath = this.getServletContext().getRealPath("WEB-INF/images");
        String path = basePath + File.separator + picture;
        File file = new File(path);
        // 如果路径不存在，证明上传失败 不需要创建路径
        if (!file.exists()) {
            return;
        }
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[1024*8];
        int len;
        ServletOutputStream os = response.getOutputStream();
        while ((len=fis.read(buf))!=-1) {
            os.write(buf,0,len);
        }
    }
}
